﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using WatiN.Core;
using WebAutomation.Browsers;

namespace WebAutomation
{
    public class AppCommand : CommandBase
    {
        public AppCommand(WebBrowserObject browserObject)
        {
            this.Initialize(browserObject);

        }

        public override bool ExecuteCommand(WebBrowserObject browserObject, string[] parameter, string url, string testRepo, string testResultLocation, string dbConnString, ref System.Data.DataSet dataFromDB, ref TestLineResult testLineResult, ref bool stopTest, WebAutoUtils.ITestDataExceptionRules testDataExceptionRules)
        {
            string command = parameter[0];
            testLineResult.LineCommand = command;
            testLineResult.LineParameter = parameter[1];
            testLineResult.LineSubCommand = command;
            if (this.BrowserObject == null)
            {
                this.BrowserObject = browserObject;
            }
            try
            {

                switch (command.ToLower())
                {
                    case "run":
                        string appToRun = "";
                        string param = "";
                        if(parameter[1].Contains("#"))
                        {
                            appToRun = parameter[1].Split('#')[0];
                            param = parameter[1].Split('#')[1];
                        }else
                        {
                            appToRun = parameter[1];
                        }

                        RunApp(appToRun, param);
                        testLineResult.LinePassed = true;
                        break;
                    default:
                        testLineResult.IsFrameworkError = false;
                        testLineResult.LineMessage = "Error.The sub command "+command+" is unknown.";
                        testLineResult.LinePassed = false;
                        break;

                }






            }
            catch (Exception ex)
            {
                testLineResult.IsFrameworkError = true;
                testLineResult.LineMessage = "Error." + ex.Message + "." + ex.StackTrace;
                testLineResult.LinePassed = false;
            }

            return testLineResult.LinePassed;
        }

        public virtual void RunApp(string fullPathToApp,string appCommandLineArguments)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo(fullPathToApp);
            startInfo.Arguments = appCommandLineArguments;
            Process.Start(startInfo);

        }
    }
}
